//
//  YDUserDatabase.swift
//  YDPerfectServer
//
//  Created by rowena on 2019/8/2.
//

import Foundation
import PerfectMySQL

/** 注册返回 */
enum YDUserRegister {
    /** 注册成功 */
    case Success
    /** 已存在 */
    case Exist
    /** 注册失败 */
    case Failure
}


class YDUserDatabase : YDDatabase {

    override init() {
        super.init()
        
        createTable()
    }
    
    /**
     * 创建数据库列
     */
    func createTable() {
        //创建表的SQL语句
        let statement = "CREATE TABLE user (user_name VARCHAR(32), user_password VARCHAR(32), user_token VARCHAR(32), user_time VARCHAR(32))"
        //1 创建表格
        let querySuccess_create = mysql.query(statement: statement)
        guard querySuccess_create else { return }
    }
    
    /**
     * 插入数据
     * @pram userName 用户名
     * @pram userPassword 用户密码
     * @pram userToken 用户Token
     * @pram userTime 注册事件
     * @return 返回插入结果 Success：成功 Exist：数据已存在 Failure：插入失败
     */
    func insertUserData(userName: String, userPassword: String, userToken: String, userTime: String) -> YDUserRegister {
        
        let statement = "select user_name, user_password from user where user_name = '\(userName)'"
        //查询该账号是否已存在
        if mysql.query(statement: statement) && mysql.storeResults()?.next() != nil {
            print("改账号已存在")
            return YDUserRegister.Exist
        } else {
            let userCode = UUID().uuidString.prefix(32)
            let date = Date()
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let userTime = dateFormatter.string(from: date)
            
            let querySuccess_create = mysql.query(statement: "INSERT INTO user VALUES (\(userName), '\(userPassword)', '\(userCode)', '\(userTime)')")
            guard querySuccess_create else {
                
                return YDUserRegister.Failure
            }
        }
        return YDUserRegister.Success
    }
    
    /**
     * 搜索数据库
     * @pram userName 用户名
     * @pram userPassword 密码
     *
     * @return 返回用户Token
     */
    func selectUserData(userName: String, userPassword: String) -> String {
        
        let statement = "select user_name, user_password, user_token from user where user_name = '\(userName)' and user_password = '\(userPassword)'"
        var userToken: String = ""
        //已存在该账号
        if mysql.query(statement: statement) {
            let results = mysql.storeResults()
 
            results?.forEachRow(callback: { (element) in
                guard let json = try? element.jsonEncodedString() else { return }
                let jsonArray: Array<String> = self.getArrayFromJSONString(jsonString: json)
                userToken = jsonArray[2]
            })
            return userToken
        }
        return userToken
    }
    
    /**
     * 删除数据
     * @pram userName 用户名
     *
     * @return 返回删除是否成功 false：删除失败 true：删除成功
     */
    func deleteUser(userName: String) -> Bool {
        let statement = "delete from user where user_name = '\(userName)'"
        return mysql.query(statement: statement)
    }
    
    /**
     * JSON字符串转换为字符串数组
     * @pram jsonString JSON字符串
     *
     * @return 返回字符串数组
     */
    func getArrayFromJSONString(jsonString: String) -> Array<String> {
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if array != nil {
            return array as! Array
        }
        return array as! Array
        
    }
}
